package com.wjc.server.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wjc.server.dto.CategoryDto;
import com.wjc.server.dto.PageDto;
import com.wjc.server.entity.Category;
import com.wjc.server.entity.CategoryExample;
import com.wjc.server.mapper.CategoryMapper;
import com.wjc.server.util.CopyUtil;
import com.wjc.server.util.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;


@Service
public class CategoryService {
    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private SnowFlake snowFlake;

    //查询
    public void list(PageDto pageDto){
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        CategoryExample categoryExample = new CategoryExample();
                categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList= categoryMapper.selectByExample(categoryExample);
        PageInfo<Category> pageInfo=new PageInfo<>(categoryList);
        pageDto.setTotal(pageInfo.getTotal());

        List<CategoryDto> categoryDtosList = CopyUtil.copyList(categoryList,CategoryDto.class);
        pageDto.setList(categoryDtosList);

    }

    //查所有数据
    public List<CategoryDto> all( ){
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList= categoryMapper.selectByExample(categoryExample);
        List<CategoryDto> categoryDtosList = CopyUtil.copyList(categoryList,CategoryDto.class);
        return categoryDtosList;
    }

    //保存
    public void save(CategoryDto categoryDto){

        Category category=CopyUtil.copy(categoryDto,Category.class);
        if (ObjectUtils.isEmpty(category.getId())){
            //新增
            category.setId(snowFlake.nextId());
            categoryMapper.insert(category);
        }else {
            categoryMapper.updateByPrimaryKey(category);
        }

    }


    @Transactional
    public void delete(Long id){
        deleteChildren(id);
        categoryMapper.deleteByPrimaryKey(id);
    }

    public void  deleteChildren(Long id){
        Category category = categoryMapper.selectByPrimaryKey(id);
        if(category.getParent() == 0){
            //如果是一级分类，则删除其下的所有二级分类
            CategoryExample categoryExample=new CategoryExample();
            CategoryExample.Criteria criteria = categoryExample.createCriteria();
            criteria.andParentEqualTo(id);
            categoryMapper.deleteByExample(categoryExample);
        }
    }



}
